package com.ruoyi.web.service;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class C2CodeSubmitterCloudService {

    @Autowired
    private DruidDataSource druidDataSource;

    /**
     * 获取最近30天 `fullName` 出现次数前10名及其次数
     *
     * @return 排序后的前10名数据
     */
    public List<Map<String, Object>> getTop10FullNameCounts() {
        List<Map<String, Object>> result = new ArrayList<>();

        // 获取最近30天的开始和结束时间
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime thirtyDaysAgo = now.minusDays(30);

        String startTime = thirtyDaysAgo.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        String endTime = now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

        // SQL 查询语句
        String sql = "SELECT moduleName, COUNT(*) AS count " +
                "FROM code_merge_info " +
                "WHERE mergeTime >= ? AND mergeTime < ? " +
                "GROUP BY moduleName " +
                "ORDER BY count DESC " +
                "LIMIT 10";

        try (Connection conn = druidDataSource.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            // 设置查询参数
            stmt.setString(1, startTime);
            stmt.setString(2, endTime);

            // 执行查询并处理结果
            try (ResultSet rs = stmt.executeQuery()) {
                while (rs.next()) {
                    Map<String, Object> data = new HashMap<>();
                    data.put("moduleName", rs.getString("moduleName"));
                    data.put("count", rs.getInt("count"));
                    result.add(data);
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return result;
    }
}
